package com.yumeko.mapper;

import java.net.Socket;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try (// 封装Request对象和Response对象
             var inputStream = socket.getInputStream();
             var outputStream = socket.getOutputStream();
        ) {
            var request = new Request(inputStream);
            var response = new Response(outputStream);
            // 静态资源处理
            if (mapper.mapUri.containsKey(request.getUrl())) {
                response.outputHtml(mapper.mapUri.get(request.getUrl()));
            } else if (mapper.servletMap.containsKey(request.getUrl())){
                // 动态资源servlet请求
                var httpServlet = mapper.servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
